import 'dart:math';

import 'package:flutter/material.dart';

class CustomPainterPage extends StatefulWidget {
  const CustomPainterPage({Key? key}) : super(key: key);

  @override
  _CustomPainterPageState createState() => _CustomPainterPageState();
}

class _CustomPainterPageState extends State<CustomPainterPage>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;

  final List<XueHua> _list = List.generate(100, (index) => XueHua());

  @override
  void initState() {
    _animationController =
        AnimationController(duration: const Duration(seconds: 1), vsync: this)
          ..repeat();
    super.initState();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("自定义"),
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
            gradient: LinearGradient(
                colors: [Colors.blue, Colors.lightBlueAccent, Colors.white],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                stops: [0, 0.7, 1.0])),
        child: AnimatedBuilder(
          animation: _animationController,
          builder: (BuildContext context, Widget? child) {
            for (var element in _list) {
              element.fill();
            }
            return CustomPaint(
              painter: MyPainter(_list),
            );
          },
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  late Paint _paint;
  late List<XueHua> _list;

  MyPainter(List<XueHua> list) {
    _list = list;
    _paint = Paint();
    _paint.color = Colors.white;
  }

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawCircle(size.center(const Offset(0, 100)), 50, _paint);
    canvas.drawOval(
        Rect.fromCenter(
            center: size.center(const Offset(0, 250)), width: 150, height: 250),
        _paint);

    for (var _xueHua in _list) {
      canvas.drawCircle(Offset(_xueHua.x, _xueHua.y), _xueHua.radius, _paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

class XueHua {
  double x = Random().nextDouble() * 400;
  double y = Random().nextDouble() * 400;
  double radius = Random().nextDouble() * 2 + 2;
  double velocity = Random().nextDouble() * 4 + 2;

  fill() {
    y += velocity;
    if (y > 800) {
      y = 0;
      x = Random().nextDouble() * 400;
      radius = Random().nextDouble() * 2 + 2;
      velocity = Random().nextDouble() * 4 + 2;
    }
  }
}
